package com.youdoneed.friends.common.util;

import com.google.gson.Gson;
import com.youdoneed.base.common.OkHttpUtils;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

public class FaceParamUtil {
    private final static Logger logger = LoggerFactory.getLogger(FaceParamUtil.class);

    public static String setParam(String msg_type, String user_id, String searchId, String type, String pathName1, String pathName2) {
        String data = "";
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            Map<String, Object> map = new HashMap<String, Object>();
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            if (StringUtils.hasText(pathName1)) {
                Request request1 = new Request.Builder().url(pathName1).get().build();
                InputStream file1 = OkHttpUtils.callForStream(request1);
                byte[] byt1 = StreamUtils.copyToByteArray(file1);
                String fileBase641 = encoder.encodeToString(byt1);
                String fileMd51 = DigestUtils.md5DigestAsHex(byt1);

                Map<String, String> map1 = new HashMap<String, String>();
                map1.put("image", fileBase641);
                map1.put("md5", fileMd51);
                list.add(map1);
                file1.close();
            }
            if (StringUtils.hasText(pathName2)) {
                Request request2 = new Request.Builder().url(pathName2).get().build();
                InputStream file2 = OkHttpUtils.callForStream(request2);
                byte[] byt2 = StreamUtils.copyToByteArray(file2);
                String fileBase642 = encoder.encodeToString(byt2);
                String fileMd52 = DigestUtils.md5DigestAsHex(byt2);

                Map<String, String> map2 = new HashMap<String, String>();
                map2.put("image", fileBase642);
                map2.put("md5", fileMd52);
                list.add(map2);
                file2.close();
            }
            if (StringUtils.hasText(pathName1) || StringUtils.hasText(pathName2)) {
                map.put("content", list);
            }

            map.put("msg_type", msg_type);
            if (StringUtils.hasText(searchId)) {
                map.put("searchId", searchId);
            }
            if (StringUtils.hasText(user_id)) {
                map.put("userId", user_id);
            }
            if (StringUtils.hasText(type)) {
                map.put("type", type);
            }
            Gson gson = new Gson();
            String param = gson.toJson(map).toString();
            data = "data=" + URLEncoder.encode(param, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
